//获取光标
$("#username").focus(function () {
    $("#tuan").show()
});
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tuan").length == 0 && $(e.target).closest("#username").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tuan").hide()
    }
})
var dataconlog = [];
//查询列表
$(function () {
    $("#tuan").hide();

    getCodeList();
});
function getCodeList() {

    var user_data = {
        ROLE_ID: sessionStorage.getItem("checkId"),
        "useNumber":$("#jobnumber").val().trim(),
        "userName":$("#names").val().trim(),

    }
    var succCallBack = function (data, status, response) {
        console.log(data.roleList_z)
        if(data.roleList_z!="") {
              /*  if (v.ROLE_ID == sessionStorage.getItem("roleId_to_roleForm")) {


                }*/
            couponlists(data.roleList_z)
        }else {
            couponlists(0)
            $("#tabletables_paginate").hide()
        }
    };
    return web.doAjax(root.accessInter.access_listRolesApi, 'post', user_data, succCallBack);
}

//添加用户
function addCodeFun(name,id) {
    if (dataconlog == null) {
        save(id)
        $("#tuan").hide();
    }else{
        var isAdd = true;
        for (var i = 0; i < dataconlog.length; i++) {
            if(dataconlog[i] == id){
                isAdd = false;
            }
        }
        if(isAdd == true){
            save(id)
            dataconlog.push(id)
            $("#tuan").hide();
            layer.msg('该用户添加成功', {icon: 1, time: 1000});
        }else {
            save(id)
            $("#tuan").hide();
        }
    }
}



console.log(sessionStorage.getItem("roleId_to_roleForm"))
//渲染表格
var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];
function couponlists(data, index){
    dataSource.splice(0,dataSource.length);//清空数组
    $.each(data, function (i, field) {
        if (field.ROLE_ID == sessionStorage.getItem("roleId_to_roleForm")) {
            var rowData = new Array();
            rowData.push(field.NUMBER);
            rowData.push(field.USERNAME);
            rowData.push(field.NAME);
            rowData.push(field.USER_ID);
            dataSource.push(rowData);
        }
    });

    initData(dataSource);

    function initData(dataSource) {

        var dttable = $('#tabletables').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#tabletables").DataTable({
            "fnDrawCallback" : function(){
                this.api().column(0).nodes().each(function(cell,i){
                    cell.innerHTML = i+1;

                });
            },
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": true,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu":[30,50,100],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[0]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 1
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = row[1]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets":2
                },  {
                    "render": function (data, type, row, meta) {
                        var val = row[2]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 3
                },{
                    "render": function (data, type, row, meta) {
                       var val='<span id="removeUEl'+row[0]+'"><a style="color: #0f9ae0" onclick="dele('+row[3]+')">移除</a><span class="userId" style="display:none">'+row[0]+'</span></span>'
                        return val;
                    },
                    "targets": 4
                },


            ]
        });

    };
}

//用户名及姓名查询
function myFunction(){
    var manager=$("#username").val();
    var user_data = {
        keywords:$("#username").val()
    }
    var succCallBack = function (data, status, response) {
        if(data.userName !=""){
            var jsonObj =data.userName;
            if(jsonObj==""){
                $("#tuan").html("<li>无数据</li> ");
            }else {
                var optionstring = "";
                for (var  i= 0; i < jsonObj.length; i++) {
                    optionstring += '<li onclick="addCodeFun(this.innerHTML,\''+ jsonObj[i].USER_ID+ '\')"> 账号:' + jsonObj[i].USERNAME +'&nbsp;&nbsp;&nbsp;姓名:'+jsonObj[i].NAME+ '</li>';
                }
                $("#tuan").html(optionstring);
            }
        }else{
            $("#tuan").html("<li>无数据</li> ");
        }
    }
    web.doAjax(root.accessInter.access_listUsername,'post',user_data, succCallBack);
}

//添加
function save(id) {
    var roleEls = id;
    console.log(roleEls)
        $.ajax({
            type: "POST",
            url: root.accessInter.access_addUsernameApi,
            cache: false,  //禁用缓存
            dataType: "json",
            data: {
                USER_ID: roleEls,
                ROLE_ID: sessionStorage.getItem("roleId_to_roleForm")
            },  //传入组装的参数
            success: function (data) {
console.log(data)


                if(data.code==200){
                    layer.msg('该用户添加成功', {icon: 1, time: 1000});
                    getCodeList();
                }else {
                    layer.msg('角色已经存在此用户', {icon: 1, time: 1000});
                }

            },
        });
    }
    //删除
function dele(id) {
    $.ajax({
        type: "POST",
        url: root.accessInter.deleteOnlyUserIdApi,
        cache: false,  //禁用缓存
        dataType: "json",
        data: {
            USER_ID: id,
            ROLE_ID:sessionStorage.getItem("roleId_to_roleForm")
        },  //传入组装的参数
        success: function (data) {
            layer.msg('移除成功', {icon: 1, time: 1000});
            getCodeList();
        },
    });
}